var fs = require('fs');
var dbPath = './da.json'
//查询所有
///node的精华，封装异步api
exports.find = (callback) => {
    fs.readFile(dbPath, 'utf8', (err, data) => {
        if (err) {
            return callback(err);
        }
        callback(null, JSON.parse(data).students);
    })
}
exports.findById = (id, callback) => {
    fs.readFile(dbPath, 'utf8', (err, data) => {
        if (err) {
            return callback(err);
        }
        var dataObj = JSON.parse(data).students;
        var result = dataObj.find((item)=> {
            return item.id === parseInt(id);
        })
        callback(null, result);
    })
}
// 保存数据
exports.save = (parmes, callback) => {
    fs.readFile('./da.json', 'utf8', (err, data) => {
        if (err) {
            return callback(false)
        }
        // console.log(data);
        var dataObj = JSON.parse(data);
        var age = parmes.age;
        parmes.id = dataObj.students[dataObj.students.length - 1].id + 1;
        parmes.age = parseInt(age);
        dataObj.students.push(parmes);
        fs.writeFile('./da.json', JSON.stringify(dataObj), 'utf8', (err) => {
            if (err) {
                return callback(false);
            }
            callback(true);
        })
    })
}
//更新数据
exports.updateById = (student, callback) => {
    fs.readFile('./da.json', 'utf8', (err, data) => {
        if (err) {
            return callback(false)
        }
        // console.log(data);
        var dataObj = JSON.parse(data).students;
        student.id = parseInt(student.id);
        //遍历，返回满足条件的对应项
        var stu = dataObj.find((item) => {
            return item.id === student.id;
        })
        for (var key in student) {
            stu[key] = student[key];
        }
        fs.writeFile('./da.json', JSON.stringify({
            students: dataObj
        }), 'utf8', (err) => {
            if (err) {
                return callback(false);
            }
            callback(true);
        })
    })
}

// 删除数据
exports.delete = (id, callback) => {
    fs.readFile(dbPath, 'utf8', (err, data) => {
        if (err) {
            return callback(false);
        }
        var dataObj = JSON.parse(data).students;
        var delIndex = dataObj.findIndex((item) => {
            return item.id === parseInt(id);
        })
        dataObj.splice(delIndex, 1);
        fs.writeFile(dbPath, JSON.stringify({
            students: dataObj
        }), 'utf8', (err) => {
            if (err) {
                return console.log('err');
            }
            console.log('success');
        })
        callback(true);
    })
}